﻿using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;

namespace TestLog
{
    public static class LogFileExtension
    {
        public static IServiceCollection AddLogFileExtension(this IServiceCollection services, LogFileConfig logFileModel)
        {
            if (!logFileModel.Enable) return services;

            var logger = new LoggerConfiguration()
                .Enrich.FromLogContext()
                .WriteTo.Async(configure =>
                    {

                        configure.File("C:\\mnt\\test.txt", rollingInterval: RollingInterval.Day,
                            outputTemplate:
                            "[{Timestamp:HH:mm:ss} {Level:u3} {ThreadId}] {Message}{NewLine}{Exception}");

                        configure.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Code);
                    }
                );



            //var logger = new LoggerConfiguration()
            //    .Enrich.FromLogContext()
            //    .WriteTo.Map(
            //        le => new Tuple<DateTime, LogEventLevel>(
            //            new DateTime(le.Timestamp.Year, le.Timestamp.Month, le.Timestamp.Day), le.Level),
            //        (key, log) => log.File(Path.Combine(logFileModel.DirName, $"{key.Item2}", $"{key.Item2.ToString().ToLower()}-.log"), logFileModel.LogEventLevel,
            //            rollingInterval: logFileModel.RollingInterval, retainedFileCountLimit: logFileModel.RetainedFileCountLimit, fileSizeLimitBytes: null));

            if (logFileModel.FilterLogLevelDic != null)
            {
                //过滤日志
                foreach (var level in logFileModel.FilterLogLevelDic)
                {
                    logger.MinimumLevel.Override(level.Key, level.Value);
                }
            }

            Log.Logger = logger.CreateLogger();

            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

            return services;



        }
    }
}
